package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/zeromicro/go-zero/core/jsonx"
	"jd_srv/cache"
	"jd_srv/models"
	"time"

	"jd_srv/internal/svc"
	"jd_srv/jd"

	"github.com/zeromicro/go-zero/core/logx"
)

type ShowGoodsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewShowGoodsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ShowGoodsLogic {
	return &ShowGoodsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ShowGoodsLogic) ShowGoods(in *jd.ShowGoodsRequest) (*jd.ShowGoodsResponse, error) {
	// todo: add your logic here and delete this line

	var goods []*models.Goods
	key := fmt.Sprintf("goods_%d", in.GoodsId)
	cacheData, _ := cache.Rdb.Get(l.ctx, key).Result()

	if cacheData == "" {
		models.DB.Where("id=?", in.GoodsId).Find(&goods)
		jsonData, _ := jsonx.Marshal(goods)
		cache.Rdb.Set(l.ctx, key, jsonData, time.Hour)
	} else {
		err := json.Unmarshal([]byte(cacheData), &goods)
		if err != nil {
			return nil, err
		}
	}
	return &jd.ShowGoodsResponse{}, nil
}
